package models

import (
	"github.com/beego/beego/v2/client/orm"
	"github.com/beego/beego/v2/core/logs"
	"github.com/beego/beego/v2/server/web"
	"rate/common/consts"
	"rate/common/exception"
	"rate/common/util/objectUtils"
	"rate/common/util/secret"
	"rate/common/util/seqUtils"
	"rate/pojo/ao"
	"rate/pojo/entity"
)

// CreateMember 创建会员
func CreateMember(member entity.Member) error {
	_, err := Orm.Insert(&member)
	if err != nil {
		logs.Error("member create fail,%s", err.Error())
		return exception.NewSystemError()
	}
	return nil
}

// FindByName 通过名称查找
func FindByName(name string) (*entity.Member, error) {
	member := entity.Member{Name: name}
	if err := Orm.Read(&member, "Name"); err != orm.ErrNoRows && err != nil {
		logs.Error("find member by name error, %s", err.Error())
		return nil, exception.NewSystemError()
	}
	return &member, nil
}

// CreateMemberWithAo 通过页面数据创建vo
func CreateMemberWithAo(ao ao.MemberAo) (*entity.Member, error) {
	// 判断会员名是否存在
	cm, err := FindByName(ao.Name)
	if err != nil {
		return nil, err
	}
	if cm.Id != 0 {
		return nil, exception.NewParamError()
	}
	var m entity.Member
	objectUtils.ObjectCopy(&m, &ao)
	m.Id = seqUtils.GetSnow()
	m.Password = secret.Md5(m.Password + web.AppConfig.DefaultString("PasswordSecret", "0.0"))
	return &m, CreateMember(m)
}

// FindCodeByEmail 通过邮箱查找可用的验证码(暂未使用)
func FindCodeByEmail(email string, codeType int) entity.EmailRecord {
	code := entity.EmailRecord{
		Email: email,
	}
	if err := Orm.Read(&code, "Email", "Result", "Status", "CodeType"); err != nil {
		logs.Error("query error,%s", err)
	}
	return code
}

// InsertEmailRecord 插入验证码发送记录
func InsertEmailRecord(code, email string) {
	record := entity.EmailRecord{
		Id:       seqUtils.GetSnow(),
		Email:    email,
		Code:     code,
		CodeType: consts.CodeTypeRegister,
	}
	_, _ = Orm.Insert(&record)
}
